package com.founder.chd_daily_query.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.founder.chd_daily_query.service.RedisPresentService;
import com.founder.chd_daily_query.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class RedisPresentServiceImpl implements RedisPresentService {

    @Autowired
    private RedisTemplate <String,String> redisTemplate;


    @Override
    public List<JSONObject> getMetaInfo(String key,int num) {

        Set<String> range = redisTemplate.opsForZSet().range(key, 0, -1);
        if(range==null){
            return null;
        }

        List<JSONObject> list =new ArrayList<JSONObject>();
        range.forEach(r ->{
            list.add(JsonUtil.parse(r));
        });
        return getByPage(list,num);
    }

    @Override
    public List<JSONObject> getMetaInfoAccurately(String model, String field, String value, Integer num) throws ClassNotFoundException, NoSuchMethodException {
        Set<String> range = redisTemplate.opsForZSet().range(model, 0, -1);
        List<JSONObject> res = new ArrayList<JSONObject>();
        range.forEach(s -> {
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONArray o = jsonObject.getJSONArray(model);
            String o1 = (String)o.getJSONObject(0).get(field);

            if(o1!=null && o1.equals(value)){
                res.add(JsonUtil.parse(s));
            }
        });
        if(range==null){
            return null;
        }
//        List<JSONObject> list =new ArrayList<JSONObject>();
//        range.forEach(r ->{
//            list.add(JsonUtil.parse(r));
//        });
        return getByPage(res,num);
    }

    private List<JSONObject> getByPage(List<JSONObject> sample, int num){
        if(sample.size()==0){
            return null;
        }
        if(num>sample.size()){
            num=sample.size();
        }
        return sample.subList(0,num);
    }
}
